package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/6 19:39
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 */
public class Title34 {

    public int[] searchRange(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] == target) {
                while (nums[left] != target) {
                    left++;
                }
                while (nums[right] != target) {
                    right--;
                }
                return new int[]{left, right};
            } else if (nums[middle] > target) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return new int[]{-1, -1};
    }

    public int[] searchRange1(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int middle = left + (right - left) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            }else{
                //找左侧和右侧 middle
                while (nums[left] != nums[middle]) {
                    left++;
                }
                while (nums[right] != nums[middle]) {
                    right--;
                }
                return new int[]{left, right};
            }
        }
        return new int[]{-1, -1};
    }

    public static void main(String[] args) {

    }
}
